package socket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**服务器*/
public class Server {
    private ServerSocket serverSocket;
//    private List<PrintWriter> allOut = new ArrayList<>();
    private Map<String,PrintWriter> allOut = new HashMap<>();
    public Server(){
        System.out.println("正在启动服务器");
        try {
            serverSocket = new ServerSocket(8088);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("服务器启动完毕");
    }
    public void start(){
            try {
                while (true){
                    System.out.println("等待客服端连接...");
                    Socket socket = serverSocket.accept();
                    System.out.println("客服端连接上了！");

                    Runnable handler = new ClientHandler(socket);
                    Thread t = new Thread(handler);
                    t.start();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    private class ClientHandler implements Runnable{
        private Socket socket;
        private String host;//记录客户端的ip地址
        private String nickname;
        public ClientHandler(Socket socket){
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }
        @Override
        public void run() {
            PrintWriter pw = null;
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                nickname = br.readLine();

                OutputStream out = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(out,StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw,true);

                synchronized (allOut){
//                    allOut.add(pw);
                    allOut.put(nickname,pw);
                }

                broadcast(nickname+"["+host+"]"+"上线了，当前在线人数："+allOut.size());

                String message;
                while ((message= br.readLine())!=null){
                    if(message.startsWith("@")){
                        sendMessageToSomeone(message);
                    }else {
                        broadcast(nickname+"["+host+"]"+"说："+message);
                    }
                }
            } catch (IOException e) {

            } finally {
                synchronized (allOut){
                    allOut.remove(nickname);
                }
                broadcast(nickname+"["+host+"]"+"下线了,当前在线人数："+allOut.size());
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        private void broadcast(String message){
            System.out.println(message);
            synchronized (allOut){
//                for (PrintWriter o : allOut){
//                    o.println(message);
//                }
                for (PrintWriter o : allOut.values()){
                    o.println(message);
                }
            }
        }
        public void sendMessageToSomeone(String message){
            if(message.matches("@.+:.+")){
                String toNickName = message.substring(1,message.indexOf(":"));
                if(allOut.containsKey(toNickName)){
                    PrintWriter pw = allOut.get(toNickName);
                    String toMessage = message.substring(message.indexOf(":")+1);
                    pw.println(nickname+"悄悄对你说："+toMessage);
                }else {
                    PrintWriter pw = allOut.get(nickname);
                    pw.println("该用户不存在");
                }
            }else {
                PrintWriter pw = allOut.get(nickname);
                pw.println("私聊格式不正确，格式应为@对方昵称：私聊消息");
            }
        }
    }
}

